package com.dream.xcarrecorder.test;

import android.media.AudioFormat;
import android.media.Image;
import android.media.MediaFormat;

import com.dream.libxrec.player.AudioDecoder;
import com.dream.libxrec.player.DecodeCallback;
import com.dream.libxrec.player.PCMPlayer;

public class AudioPlayRateTester {

    private final AudioDecoder mAudioDecoder = new AudioDecoder();
    private PCMPlayer mPcmPlayer = null;
    private float mAudioRate = 1;
    private float mAudioTempo = 1;

    //音频解码回调
    private final DecodeCallback mOnDataListener =
            new DecodeCallback() {
                @Override
                public void initVideo(MediaFormat format) {}

                @Override
                public void initAudio(MediaFormat format) {
                    final int sampleRate =
                            format.getInteger(MediaFormat.KEY_SAMPLE_RATE);
                    final int channelNum =
                            format.getInteger(MediaFormat.KEY_CHANNEL_COUNT);
                    mPcmPlayer = new PCMPlayer(4060,sampleRate,channelNum,
                            AudioFormat.ENCODING_PCM_16BIT);

                    if (mAudioRate!= 1){
                        mPcmPlayer.setRate(mAudioRate);
                    }else if (mAudioTempo != 1){
                        mPcmPlayer.setTempoChange(mAudioTempo);
                    }
                }

                @Override
                public void onVideoDecode(Image image, long pts) {}

                @Override
                public void onAudioDecode(byte[] pcm, int size, long pts) {
                    if (mPcmPlayer!= null){
                        mPcmPlayer.play(pcm,size);
                    }
                }

                @Override
                public void onFinish(int type) {}
            };

    public void play(String audioPath){
        if (mAudioDecoder.isDecoding()){
            return;
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    mAudioDecoder.init(audioPath, mOnDataListener);
                    mAudioDecoder.start();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }

    public void setRate(float rate){
        this.mAudioRate = rate;
        this.mAudioTempo = 1;
    }

    public void setTempo(float rate){
        this.mAudioTempo = rate;
        this.mAudioRate = 1;
    }
}
